//
//  CZTabBar.swift
//  CZWeibo
//
//  Created by 左凯旭 on 16/8/9.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

protocol CZTabBarDelegate:NSObjectProtocol {
    
    //声明方法
    func tabBarButtonClick()
    
}


class CZTabBar: UITabBar {

   // 声明一个代理
    weak var czdelegate:CZTabBarDelegate?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        //设置UI
        setupUI()
    }
    //代码实现的时候必须要写
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    func setupUI(){
        //添加控件
        addSubview(middleButton)
        
       
    }
    
    //给子控件设置frame
    override func layoutSubviews() {
        super.layoutSubviews()
        
        
        //设置四个tabbarButton的位置
        //遍历
        //设置四个button的宽
        let childW = self.frame.width * 0.2
        var index: CGFloat = 0
        
        for value in self.subviews {
            
            //判断遍历的是不是属于UIBarButton
            if value.isKindOfClass(NSClassFromString("UITabBarButton")!) {
                
                value.frame.size.width = childW
                value.frame.origin.x = index * childW
                
                index++
                if index == 2 {
                    index++
                }
            }
        }
  
        //设置撰写按钮的frame
        middleButton.center.x = self.frame.width * 0.5
        middleButton.center.y = self.frame.height * 0.5
        
        
    }
    
    //中间的按钮的点击事件
    func btnClick(){
       czdelegate?.tabBarButtonClick()
    }
    
    
    
    // MARK: - 懒加载控件
    // 撰写按钮
    
    lazy var middleButton:UIButton = {
        
        let btn = UIButton()
        
        btn.addTarget(self, action: "btnClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        btn.setBackgroundImage(UIImage(named:"tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        btn.setBackgroundImage(UIImage(named:"tabbar_compose_button"), forState: UIControlState.Normal)
        
        btn.setImage(UIImage(named:"tabbar_compose_icon_add_highlighted"), forState: UIControlState.Selected)
        btn.setImage(UIImage (named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        
          // 自适应
        btn.sizeToFit()
        
        return btn
    }()
    
}




